package com.justgame.project.cloud.common.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Map;

public class HttpUtil {


    /**
     * Get请求
     * @param url
     * @return
     */
    public static Object get(String url){
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return JSONObject.parseObject(result.toString());
    }

    /**
     * 获取重定向
     * @param url
     * @return
     */
    public static String getPostRedirectUrl(String url, String params){
        HttpURLConnection con = sendPost(url,params,null);
        return con.getHeaderField("Location");
    }

    /**
     * POST请求响应
     * @param url
     * @return
     */
    public static String post(String url, String params,Map<String, String> headers) {
        HttpURLConnection con = sendPost(url,params,headers);
        // 读取返回内容
        StringBuilder buffer = new StringBuilder();
        try {
            //一定要有返回值，否则无法把请求发送给server端。
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
            String temp;
            while ((temp = br.readLine()) != null) {
                buffer.append(temp);
                buffer.append("\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }

    /**
     * 获取POST请求连接
     * @param url
     * @return
     */
    private static HttpURLConnection sendPost(String url, String params,Map<String, String> headers) {
        URL u = null;
        HttpURLConnection con = null;
        // 尝试发送请求
        try {
            u = new URL(url);
            con = (HttpURLConnection) u.openConnection();
            //// POST 只能为大写，严格限制，post会不识别
            con.setRequestMethod("POST");
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            if (headers != null){
                headers.forEach(con::setRequestProperty);
            }
            OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), StandardCharsets.UTF_8);
            osw.write(params);
            osw.flush();
            osw.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (con != null) {
                con.disconnect();
            }
        }
        // 读取返回内容
        StringBuilder buffer = new StringBuilder();
        try {
            //一定要有返回值，否则无法把请求发送给server端。
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
            String temp;
            while ((temp = br.readLine()) != null) {
                buffer.append(temp);
                buffer.append("\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            System.out.println(buffer.toString());
        }
        return con;
    }

    /**
     * 构建请求参数
     * @param params
     * @return
     */
    public static String buildUrlParams(Map<String, Object> params){
        Iterator<String> it = params.keySet().iterator();
        StringBuilder paramStr = new StringBuilder();
        paramStr.append("?");
        while (it.hasNext()){
            String key = it.next();
            if (StringUtils.isBlank(key)){
                continue;
            }
            Object value = params.get(key);
            String valueString = "";
            if (value != null){
                try {
                    valueString += ( key + "=" + URLEncoder.encode(String.valueOf(value), "utf-8") );
                } catch (UnsupportedEncodingException e) {
                    valueString += ( key + "=" + value );
                }
            }
            if (StringUtils.isNotBlank(valueString)){
                if (paramStr.length() == 1){
                    paramStr.append(valueString);
                }else{
                    paramStr.append("&").append(valueString);
                }
            }
        }
        if (paramStr.length() == 1 ){
            return "";
        }
        return paramStr.toString();
    }


}
